package com.ddmh.p2p.socket.server;

import com.ddmh.p2p.socket.client.DownloadRequest;
import com.ddmh.p2p.socket.model.SharedFile;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * P2P服务器
 *
 * @author brant
 * @since 2024-04-12
 */
@Slf4j
public class Server {
    private final int serverPort;
    private final List<SharedFile> sharedFiles;

    public Server(int serverPort) {
        this.serverPort = serverPort;
        this.sharedFiles = new ArrayList<>();
    }

    public void start() {
        try (ServerSocket serverSocket = new ServerSocket(serverPort)) {
            System.out.println("P2P服务器已启动，监听端口：" + serverPort);

            while (true) {
                Socket clientSocket = serverSocket.accept();
                new ClientHandler(clientSocket).start();
            }
        } catch (IOException e) {
            log.error("服务器启动失败", e);
        }
    }

    private class ClientHandler extends Thread {
        private final Socket clientSocket;

        public ClientHandler(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        @Override
        public void run() {
            try (ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
                 ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream())) {

                // 接收客户端的共享文件列表
                List<SharedFile> clientSharedFiles = (List<SharedFile>) in.readObject();

                // 将客户端的共享文件列表合并到服务器的列表中
                sharedFiles.addAll(clientSharedFiles);

                // 处理下载请求
                while (true) {
                    DownloadRequest request = (DownloadRequest) in.readObject();
                    if (request != null) {
                        out.writeObject(request);
                    }
                }

            } catch (IOException | ClassNotFoundException e) {
                log.error("客户端连接异常", e);
            }
        }
    }
}